package com.yanwq.sayhi.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.meta.FileAuthority;
import com.qcloud.cos.request.DelFileRequest;
import com.qcloud.cos.request.UpdateFileRequest;
import com.qcloud.cos.request.UploadFileRequest;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * 作者：yanweiqiang。
 * 日期：2016/8/4 0004。
 */
@Service
public class COSService extends AbsCSService {

    String mBucketName = "sayhi";// 设置用户属性, 包括appid, secretId和SecretKey
    // 这些属性可以通过cos控制台获取(https://console.qcloud.com/cos)
    int appId = 10001085;
    String secretId = "AKIDxDrBZlSRFjmXvHQH0cdIQ5fSv5Ka6uaG";
    String secretKey = "lrJX4vG3QlPjG7owavLgoZ1tU96eQARr";
    COSClient cosClient;

    public COSService() {
        super();
        cosClient = new COSClient(appId, secretId, secretKey);
    }

    @Override
    public String uploadPicture(File file) throws FileNotFoundException {
        return uploadFile(file);
    }

    @Override
    public String uploadFile(File file) throws FileNotFoundException {
        UploadFileRequest uploadFileRequest = new UploadFileRequest(mBucketName, "/" + file.getName(), file.getAbsolutePath());
        String uploadFileRet = cosClient.uploadFile(uploadFileRequest);
        JSONObject jsonObject = JSONObject.fromObject(uploadFileRet);

        if (jsonObject.getInt("code") == 0) {
            return jsonObject.getJSONObject("data").getString("access_url");
        }

        return null;
    }

    /**
     * @param key the path of file on cos.
     */
    @Override
    public void remove(String key) {
        DelFileRequest delFileRequest = new DelFileRequest(mBucketName, key);
        String delFileRet = cosClient.delFile(delFileRequest);
        System.out.println("del file ret:" + delFileRet);
    }

    @Override
    public String getURL(String key) {
        return null;
    }
}
